<template>
  <div class = "quickReplyMain">
    <!-- 快捷回复标题 -->
    <div class="main-head">
      <b>{{dataType === 'customize' ? $t('webchat.SetQuickReplay') : $t('routeI18n.quickReplyMain')}}</b>
    </div>
    <!-- 快捷回复内容 -->
    <el-row class="main-body" v-show = "!isImport">
      <!-- 左侧分类 -->
      <el-col :span="6" class="box-left">
        <quickReplySort :dataType="dataType" :sortRandom="sortRandom" :currentSort="currentSort"></quickReplySort>
      </el-col>
      <!-- 右侧快捷回复内容 -->
      <el-col :span="18" class="box-right">
        <!-- 快捷回复头部搜索框 -->
        <div class = "right-header clearfix">
          <p class="sort_name">{{cuttenrSortCon}}</p>
          <div class="fr">
            <!-- 添加快捷回复按钮 -->
            <el-button
                    class = "iconfont icon-zhankai"
                    @click = "addQuickReply"><span>{{$t('webchat.addQuickReplay')}}</span></el-button>
            <!-- 导入快捷回复按钮 -->
            <el-button
                    class = "iconfont icon-daoru"
                    @click = "leadIn"><span>{{$t('config.customer.import')}}</span></el-button>
            <el-button
                    class = "iconfont icon-daochu"
                    @click = "leadOut"><span>{{$t('public.export')}}</span></el-button>
            <!-- 刷新快捷回复按钮 -->
            <el-button
                    class = "iconfont icon-shuaxin"
                    :loading = "refreshLoading"
                    @click = "refresh('click')"><span>{{$t('public.refresh')}}</span></el-button>
            <!-- 批量删除快捷回复 -->
            <el-button
                    v-show="showBatchBtn"
                    class = "iconfont icon-qiapianshangdeguanbi"
                    @click = "batchDelete"><span>{{$t('webchat.moreDel')}}</span></el-button>
            <!-- 快捷回复count数 -->
            <p class = "total" v-show="currentSort">{{$t('webchat.TotalNumber', {replyLength: replyLength})}}</p>
            <!-- 快捷回复count和翻页 -->
            <div class="pagination_box">
              <Pagination
                      v-show="!currentSort"
                      :small="true"
                      :currentPage="currentPage"
                      :count="replyLength"
                      :pageSize="20"
                      @turnPage="trunPages"
                      :totalPage="Math.ceil(replyLength/20)"
              >
              </Pagination>
            </div>
            <!-- 快捷回复搜索框 -->
            <el-input
                    size = "mini"
                    @keyup.enter.native = "searchText"
                    :placeholder = "$t('public.pleaseEnter')"
                    v-model.trim = "text">
              <i slot="suffix" @click="searchText" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
        </div>
        <!-- 快捷回复项组件 -->
        <quickReplyLi
                ref="quickReplyLi"
                :randomReply="randomReply"
                :currentSort="currentSort"
                :sortData="sortData"
                @editReply="editReply"
                :dataType="dataType"></quickReplyLi>
      </el-col>
    </el-row>
    <!-- 添加快捷回复dialog -->
    <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogShow"
            :append-to-body="true"
            width="50%"
            :before-close="dialogClose">
      <el-form :model="formData" label-width="80px" ref="dialogForm" :label-position="this.$store.state.labelPosition === 'top' ? 'top' : 'right'">
        <el-form-item :label="$t('webchat.category')">
          <el-select v-model="formData.tagParentId" :placeholder="$t('webchat.pleaseChooseCategory')" style="width: 50%">
            <el-option
                    v-for="item in sortData"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('webchat.quickWords')">
          <el-input :placeholder="$t('webchat.pleaseEnterQuickWords')" :maxlength="6" v-model="formData.quickContent" style="width: 50%">
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('business.replyContent')+ ':'">
          <el-input class="dialog_textarea" :placeholder="$t('webchat.pleaseEnterContent')" type="textarea" v-model="formData.content" rows="5" resize="none">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn " @click="dialogClose">{{$t('webchat.cancel')}}</el-button>
        <el-button class="primary_btn " type="primary" @click="saveReplyEdit">{{$t('webchat.determine')}}</el-button>
      </span>
    </el-dialog>
    <!-- 导入快捷回复组件 -->
    <bread-crumb :titleArr = "titleArr"
                 :dealEv = "true"
                 v-if = "isImport"
                 @back = "importRefresh"></bread-crumb>
    <leadInTemplate v-if = "isImport" @lindInTemSuc = "lindInTemSuc" :type="'webchat'" :dataType="dataType"></leadInTemplate>
  </div>
</template>
<script>
  import quickReplySort from './quickReplySort.vue'
  import quickReplyLi from './quickReplyLi.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import leadInTemplate from '../base/leadInTemplate.vue'
  import breadCrumb from '@/components/ui-modules/breadCrumb/BreadCrumbConfig.vue'
  import {deepClone} from '@/utils/m7Utils'
  import bus from '@/store/eventBus'
  export default {
    name: 'quickReplyMain',
    data () {
      return {
        currentSort: '',          //  当前选中的快捷回复
        sortRandom: 0,            //  刷新快捷回复分类的随机数
        cuttenrSortCon: '',       //  当前快捷回复分类标题
        randomReply: 0,           //  刷新快捷回复随机数
        sortData: [],             //  添加||编辑快捷回复的时候，下拉选择分类  &&  展示所有快捷回复的时候，展示所属分类
        replyLength: 0,           //  当前快捷回复总条数
        currentPage: 1,           //  当前页数
        dialogShow: false,        //  展示添加快捷回复的dialog
        formData: {               //  添加||编辑快捷回复dialog数据
          tagParentId: '',
          quickContent: '',
          content: ''
        },
        dialogTitle: this.$t('webchat.addQuickReplay'),    //  dialog框标题
        showBatchBtn: false,            //  展示批量删除按钮
        titleArr: [this.$t('config.channel.quickReplay'), this.$t('config.channel.ImportQuickReply')],       //  导入快捷回复面包屑标题
        text: '',                       //  快捷回复搜索框内容
        refreshLoading: false,          //  快捷回复loading展示
        isImport: false                 //  是否是快捷回复导入
      }
    },
    components: {
      quickReplySort,
      quickReplyLi,
      Pagination,
      leadInTemplate,
      breadCrumb
    },
    props: {
      dataType: {
        type: String,
        default: ''
      },
      isShowQuickReply: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      dataType() {
        this.cuttenrSortCon = '' // 切换库清空分类
        this.refresh('', 'all') // 获取右侧全部快捷回复
      },
      isShowQuickReply() { // 在线自定义快捷回复展示获取最新列表
        this.refresh()
      }
    },
    methods: {
      // 切换导入模板组件, 传入面包屑数据
      leadIn () {
        this.isImport = true
      },
      leadOut () {
        let checkCount = this.$refs.quickReplyLi.checkedCount
        let searchCon = this.$refs.quickReplyLi.searchCon
        let str = this.$t('config.channel.exportAllQuickRely')
        if (checkCount > 0 && !searchCon) {
          str = this.$t('config.channel.exportCheckedQuickRely')
        }
        if (this.currentSort && !checkCount && !searchCon) {
          str = this.$t('config.channel.exportSortQuickRely')
        }
        if (!checkCount && searchCon) {
          str = this.$t('config.channel.exportSearchQuickRely')
        }
        let list = deepClone(this.$refs.quickReplyLi.dataObj.list)
        this.$confirm(str, this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let dataObj = {
            exportAll: false,
            quickIdList: [],
            tagIdList: [],
            content: '',
            searchTagId: ''
          }
          if (checkCount > 0) {
            let arr = []
            list.forEach((item) => {
              if (item.checked) {
                arr.push(item._id)
              }
            })
            dataObj.quickIdList = arr
          }
          if (!checkCount && searchCon) {
            dataObj.content = searchCon
          }
          if (!checkCount && this.currentSort && !searchCon) {
            let arr = []
            arr.push(this.currentSort)
            dataObj.tagIdList = arr
          }
          if (!checkCount && this.currentSort && searchCon) {
            dataObj.searchTagId = this.currentSort
          }
          let data = {
            Method: this.dataType === 'customize' ? 'exportQuickReplyAgent' : 'exportQuickReply',
            Query: dataObj
          }
          this.$store.dispatch('exportQuickReply', data).then(res => {})
        }).catch(() => {})
      },
      // 导入模板之后返回主界面
      lindInTemSuc () {
        this.refresh()
      },
      trunPages (val) { // 翻页
        this.currentPage = val
        bus.$emit('getCount', {currentPage: this.currentPage, content: this.text, dataType: this.dataType})
      },
      //  刷新
      refresh (type, todo) {
        this.text = ''
        if (type !== 'click') {
          this.currentSort = ''
        }
        if (todo === 'all') {
          this.randomReply = Math.random()
        }
        this.trunPages(1)
        this.sortRandom = Math.random()
      },
      // 刷新 返回主界面的搜索
      importRefresh () {
        this.isImport = false
        this.refreshLoading = true
        window.setTimeout(() => {
          this.refreshLoading = false
        }, 400)
        this.refresh('', 'all')
      },
      //  dialog关闭事件
      dialogClose () {
        this.dialogShow = false
        this.formData = {
          tagParentId: '',
          quickContent: '',
          content: '',
          moduleType: 'webchat'
        }
      },
      //  添加快捷回复
      addQuickReply () {
        this.formData = {
          tagParentId: '',
          quickContent: '',
          content: '',
          moduleType: 'webchat'
        }
        this.dialogTitle = this.$t('webchat.addQuickReplay')
        if (this.currentSort) {
          this.formData.tagParentId = this.currentSort
        }
        this.dialogShow = true
      },
      //  保存快捷回复
      saveReplyEdit () {
        let dataClone = deepClone(this.formData)
        if (!dataClone.tagParentId) {
          this.$message.error(this.$t('webchat.pleaseChooseCategory'))
          return
        }
//        此处不要在input框上设置trim方法，input框设置trim方法的话，在resetForm的时候，无法重置掉空格
        if (!dataClone.quickContent.trim()) {
          this.$message.error(this.$t('webchat.pleaseEnterQuickWords'))
          return
        }
        if (!dataClone.content.trim()) {
          this.$message.error(this.$t('webchat.pleaseEnterContent'))
          return
        }
//        区分是公共快捷回复还是自定义快捷回复
        let actionUpdate = 'newUpdateQuickReply'
        let actionAdd = 'newAddQuickReply'
        if (this.dataType === 'customize') {
          actionUpdate = 'newUpdateAgentQuickReply'
          actionAdd = 'newAddAgentQuickReply'
        }
        let str = dataClone.content
        str = str.replace(/\{agent\}/g, '')
        str = str.replace(/\{agentName\}/g, '')
        dataClone.content = str
//        如果有_id的话，就是修改快捷回复操作，没有的话，就是添加
        if (dataClone._id) {
          this.$store.dispatch(actionUpdate, dataClone).then(res => {
            if (res && res.success) {
              this.dialogShow = false
              this.$message.success(this.$t('monitor.saveSuccess'))
              this.refresh('click')
            }
          })
        } else {
          this.$store.dispatch(actionAdd, dataClone).then(res => {
            if (res.success) {
              this.dialogShow = false
              this.$message.success(this.$t('config.customer.addSucc'))
              this.refresh('click')
            }
          })
        }
      },
//      批量删除
      batchDelete () {
        bus.$emit('deleteQuickReply', {data: true, dataType: this.dataType})
      },
      // 通过输入内容搜索第一页的内容
      searchText () {
        this.currentPage = 1
        bus.$emit('getCount', {currentPage: this.currentPage, content: this.text, dataType: this.dataType})
      }, 
      editReply (msg) {
        if (msg.dataType === this.dataType) {
          if (msg.data.category) {
            this.$set(msg.data, 'tagParentId', msg.data.category)
          }
          this.formData = deepClone(msg.data)
          this.dialogTitle = this.$t('webchat.editQuickReplay')
          this.dialogShow = true
        }
      }
    },
    mounted () {
      let self = this
//      选择某个分类  ||  选择全部分类
      bus.$on('sortActive', (msg) => {
        if (msg.dataType === self.dataType) {
          self.text = ''
          self.currentSort = msg._id
          self.cuttenrSortCon = msg.name
          if (!self.currentSort) {
            self.currentPage = 1
          }
          self.randomReply = Math.random()
        }
      })
//      获取分类数据
      bus.$on('sortChange', (msg) => {
        if (msg.dataType === self.dataType) {
          self.sortData = msg.data
        }
      })
//      编辑当前选中分类名称
      bus.$on('editSelected', (msg) => {
        if (msg.dataType === self.dataType) {
          self.cuttenrSortCon = msg.data
        }
      })
//      查询快捷回复
      bus.$on('queryReply', (msg) => {
        if (msg.dataType === self.dataType) {
          self.replyLength = deepClone(msg.count)
        }
      })
//      快捷回复全选按钮点击||重置事件
      bus.$on('checkBoxClick', (msg) => {
        if (msg.dataType === self.dataType) {
          self.showBatchBtn = msg.data
        }
      })
//      删除全部分类操作
      bus.$on('removeAllSort', (msg) => {
        if (msg.dataType === self.dataType) {
          this.refresh('', 'all')
        }
      })
    },
    beforeDestroy () {
      bus.$off('sortActive')
      bus.$off('removeAll')
      bus.$off('sortChange')
      bus.$off('queryReply')
      bus.$off('editSelected')
      bus.$off('checkBoxClick')
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .quickReplyMain
    padding 20px
  .user_pic_quick_reply
    .quickReplyMain
      height calc(100vh - 214px)
  .new-config
    .quickReplyMain
      height calc(100vh - 94px)
      overflow auto
  .main-head
    font-size 14px
    margin-bottom 20px
  .main-body
    border 1px solid #E7E7EB
    height calc(100% - 40px)
  .box-left
    height 100%
    border-right 1px solid #e7e7eb
  .right-header
    padding 6px 10px
    height 46px
    line-height 34px
    border-bottom 1px solid #e7e7eb
    width 100%
    box-sizing border-box
    .fr
      height 40px
    .total
      height 34px
      line-height 34px
      margin 0 8px
      display inline-block
    .el-input
      width 150px
    span
      cursor pointer
    .iconfont
      color $c-main
      font-size 12px
      .icon-zhankai1
        transform rotate(90deg)
        display inline-block
        color $c-main
      span
        color $cf-gray2
        margin-left 4px
    .el-button
      padding 0
      border none
      margin-left 8px
    .icon-qiapianshangdeguanbi
      color $c-pink
      span
        color $c-pink
  .sort_name
    display inline-block
    max-width calc(100% - 560px)
    overflow hidden
    text-overflow ellipsis
    white-space nowrap
    line-height 34px
  .pagination_box
    display inline-block
    margin 0 10px
    .page
      color #000
</style>
